Chef recently discovered a
function XOR(), which computes the XOR of all elements of a sequence:
XOR(a1..n) = a1 ⊕ a2 ⊕ ... ⊕ an
Chef has a sequence A with
size n. He generated a new
sequence B with size n2
using the following formula:
Bin+j+1
= (Ai+1 + Aj+1) ∀ 0 ≤ i,
j < n
Compute the value of XOR(B).
Input. The first line contains a single integer t (1 ≤ t ≤ 100) denoting the number of test cases. The description
of t test cases follows. The
first line of each test case contains a single integer n (1 ≤ n ≤ 105). The second line contains n space-separated integers a1, a2, …, an
(20 ≤ ai <
230).
Output. For each test case, print a single line containing one
integer – the answer to the problem.
Sample input |
Sample output |
1 2 1 2 |
6 |
математика
Изучим
структуру последовательности В:
при i = 0, j = 0: B1
= A1 + A1;
при i = n – 1, j = n – 1: Bn*n = An + An;
XOR(B) =
(A1
+ A1) ⊕ (A1 + A2) ⊕ (A1 + A3) ⊕ … ⊕ (A1
+ An-1) ⊕ (A1
+ An) ⊕
(A2
+ A1) ⊕ (A2 + A2) ⊕ (A2 + A3) ⊕ … ⊕ (A2
+ An-1) ⊕ (A2
+ An) ⊕
…
(An + A1) ⊕ (An + A2) ⊕ (An + A3) ⊕ … ⊕ (An + An-1) ⊕ (An + An)
Очевидно,
что (Ai + Aj) ⊕ (Aj + Ai) =
0. Слагаемые сократятся, останется
XOR(B) = (A1
+ A1) ⊕ (A2 + A2) ⊕ (A3 + A3) ⊕ … ⊕ (An + An),
что
вычисляется за линейное время.
Реализация алгоритма
#include <iostream>
using namespace std;
long long i, n, ai, res,
tests;
int main(void)
{
cin >> tests;
while (tests--)
{
cin >> n;
res = 0;
for (i = 0; i < n; i++)
{
cin >> ai;
res = res ^ (2 * ai);
}
cout << res << endl;
}
return 0;
}